package com.lzq.springblog.service;

import com.lzq.springblog.dao.BlogInfoMapper;
import com.lzq.springblog.dao.LikeInfoMapper;
import com.lzq.springblog.model.BlogInfo;
import com.lzq.springblog.model.LikeInfo;
import com.lzq.springblog.model.PageRequest;
import com.lzq.springblog.model.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class BlogService {

    @Autowired
    private BlogInfoMapper blogInfoMapper;

    @Autowired
    private LikeInfoMapper likeInfoMapper;

    public PageResult<BlogInfo> getBlogListByPage(PageRequest pageRequest) {
        log.info("执行getBlogListByPage方法");
        Integer count = blogInfoMapper.count();
        List<BlogInfo> blogs = blogInfoMapper.queryBlogListByPage(pageRequest.getOffset(),pageRequest.getPageSize());
        return new PageResult<>(count,blogs,pageRequest);
    }

    public BlogInfo getBlogDetail(Integer blogId) {
        log.info("执行getBlogDetail方法");
        return blogInfoMapper.selectBlogById(blogId);
    }
    public Integer insertBlog(BlogInfo blogInfo) {
        log.info("执行insertBlog方法");
        return blogInfoMapper.insertBlog(blogInfo);
    }

    public Integer updateBlog(BlogInfo blogInfo) {
        log.info("执行updateBlog方法");
        return blogInfoMapper.updateBlog(blogInfo);
    }

    public Integer deleteBlog(Integer blogId) {
        log.info("执行deleteBlog方法");
        return blogInfoMapper.deleteBlogById(blogId);
    }

    public Integer addBlogLike(Integer userId,Integer blogId) {
        log.info("执行addBlogLike方法");
        //查询有无这条记录,再做对应操作
        LikeInfo likeInfo = likeInfoMapper.selectIsLiked(userId,blogId);
        if(likeInfo==null) {
            likeInfoMapper.insertLikeRecord(userId,blogId);
        }else {
            likeInfoMapper.updateLikeRecord(userId,blogId);
        }
        return blogInfoMapper.addBlogLike(blogId);
    }

    public Integer cancelBlogLike(Integer userId, Integer blogId) {
        log.info("执行cancelBlogLike方法");
        likeInfoMapper.deleteLikeRecord(userId,blogId);
        return blogInfoMapper.deleteBlogLike(blogId);
    }

    public Integer getUserArticleCounts(Integer userId) {
        log.info("执行getUserArticleCounts方法");
        return blogInfoMapper.selectUserArticleCounts(userId);
    }

    public Integer getViewCounts(Integer blogId) {
        log.info("执行getViewCounts方法");
        return blogInfoMapper.selectViewCountsById(blogId);
    }

    public Integer addViewCount(Integer blogId) {
        log.info("执行addViewCount方法");
        return blogInfoMapper.addViewCountsById(blogId);
    }
}
